<?php
namespace common\services\lifang;

use linslin\yii2\curl\Curl;
use yii\base\Exception;

class LiFangTrain extends LiFang {

    /**
     * 查询火车票标准商品列表：
        1.辅助接口，确认当前用户被允许使用该标准商品，获取标准商品编号用于货源确认或车票预订；
        2.该商品相对稳定，如已经确认并获取过，可作缓存；
        3.如返回为空，请联系上级确认火车票商品对接状态以避免下单失败
     * @param string $pageNo
     * @param string $itemName
     * @param string $itemId
     * @param string $pageSize
     * @return mixed
     * @throws Exception
     */
    public function queryTrainShopList($pageNo = '', $itemName ='', $itemId = '', $pageSize = '') {
        $method = 'qianmi.elife.train.items.list';

        $params = [
            "pageNo" => $pageNo,
            "itemName" => $itemName,
            "itemId" => $itemId,
            "pageSize" => $pageSize,
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();

        $curl->setGetParams($params);

        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }

    /**
     * 查询火车票商品货源详情：
        查询火车票商品货源详情(如果已确认当前已对接有效货源，可忽略此步)：
        1.辅助接口，查询火车票标准商品货源详情，包含供货商，价格等；
        2.如返回为空，请联系上级确认保险商品对接状态以避免下单失败。
     * @param string $itemId
     * @return mixed
     * @throws Exception
     */
    public function queryTrainShopInfo($itemId = '') {
        $method = 'qianmi.elife.train.item.detail';

        $params = [
            "itemId" => $itemId,
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();
        $curl->setGetParams($params);
        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }

    /**
     * 查询所有火车站点信息
     * 查询所有火车站点信息，信息固定，可缓存客户端用于站点的展示与筛选匹配
     * @param string $from
     * @param string $to
     * @param string $date
     * @throws \Exception
     */
    public function queryTrainAllStationInfo() {
        $method = 'qianmi.elife.train.stations.list';

        $params = [

        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();
        $curl->setGetParams($params);
        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }

    /**
     * 查询火车票站到站信息(含票价)
     * 查询指定“起点站”到“终点站”在指定日期所有火车票站次信息列表，包含座位与票价信息等；不支持指定无座。
     * @param string $from
     * @param string $to
     * @param string $date
     * @throws \Exception
     */
    public function queryFromToInfo($from = '', $to ='', $date = '') {
        $method = 'qianmi.elife.train.lines.list';

        $params = [
            "from" => $from,
            "to" => $to,
            "date" => $date
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();

        $curl->setGetParams($params);

        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }

    /**
     * 12306账号登录
     * @param string $accountNo    账号
     * @param string $accountPwd   密码
     * @param string $captchaCode  验证码
     * @throws \Exception
     */
    public function queryTrainLogin($accountNo = '', $accountPwd ='', $captchaCode = '') {
        $method = 'lf.elife.train.account.login';

        $accountSecret = $this->getSecretData($accountNo);
        $passwordSecret = $this->getSecretData($accountPwd);
        $params = [
            "accountNo" => $accountSecret,
            "accountPwd" => $passwordSecret,
            "captchaCode" => $captchaCode
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();
        $curl->setGetParams($params);
        $response = $curl->get($this->api);

        $response = $this->formatResponse($response);

        $response['account'] = $accountSecret;
        $response['password'] = $passwordSecret;

        return $response;
    }

    public function getSecretData($data = '') {
        $url = \Yii::$app->params['JAVA_12306_HOST'] . '/index';
        $curl2 = new Curl();
        $curl2->setGetParams(['data' => $data]);
        $res = $curl2->get($url);

        $res = json_decode($res, true);

        return $res['data'];
    }

    /**
     * 12306账户信息查询
     * @param string $accountNo    账号
     * @param string $accountPwd   密码
     * @param string $queryType  查询类型(默认0) 0:正常查询 1:刷新数据
     * @throws \Exception
     */
    public function queryTrainAccountInfo($accountNo = '', $accountPwd ='', $queryType = '') {
        $method = 'lf.elife.train.account.detail';

        $params = [
            "accountNo" => $accountNo,
            "accountPwd" => $accountPwd,
            "queryType" => $queryType
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();
        $curl->setGetParams($params);
        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }

    /**
     * 12306账户信息更新
     * @param string $accountNo    账号
     * @throws \Exception
     */
    public function queryTrainAccountModify($accountNo = '', $passengeTypeOld ='', $passengerName = '',$sexCode = '', $certNo ='', $certType = ''
          , $passengeType ='', $phone = '',$bornDate = '', $expiryDate ='', $mail = '', $passengerNameNew = '',$certNoNew = '', $certTypeNew ='', $stuInfo = ''
        )
    {
        $method = 'lf.elife.train.account.modify';

        $params = [
            "accountNo" => $accountNo,
            "passengeTypeOld" => $passengeTypeOld,
            "passengerName" => $passengerName,
            "sexCode" => $sexCode,
            "certNo" => $certNo,
            "certType" => $certType,
            "passengeType" => $passengeType,
            "phone" => $phone,
            "bornDate" => $bornDate,
            "expiryDate" => $expiryDate,
            "mail" => $mail,
            "passengerNameNew" => $passengerNameNew,
            "certNoNew" => $certNoNew,
            "certTypeNew" => $certTypeNew,
            "stuInfo" => $stuInfo,
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();
        $curl->setGetParams($params);
        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }

    /**
     * 12306账户证件号更新
     * @param string $tradeNo   订单编号
     * @throws \Exception
     */
    public function queryTrainCertModify($accountNo = '',$passengeType = '',$passengerName = '',$certNo = '',$oldCertNo = '',$certType = '',$phone = '' ,$mail = '') {
        $method = 'lf.elife.train.cert.modify';

        $params = [
            "accountNo" => $this->getSecretData($accountNo),
            "passengeType" => $passengeType,
            "passengerName" => $passengerName,
            "certNo" => $certNo,
            "oldCertNo" => $oldCertNo,
            "certType" => $certType,
            "phone" => $phone,
            "mail" => $mail,
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();
        $curl->setGetParams($params);
        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }


    /**
     * 预订火车票
     * 预订：
        1.保险商品目前只支持千米官方非人工充值的货源，请确认货源对接正确以避免下单失败。
        2.操作结果不代表预订结果，最终预订结果由货源方决定。
     * @param string $accountNo   12306账号(密文)
     * @throws \Exception
     */
    public function queryTrainOrderCreate($accountNo = '',$accountPwd = '',$ticketModel = '',$trainNumber = '',$startTime = '',$contactName = '',
        $passagers = '' ,$itemIdTrain = '',$date = '',$to = '',$from = '',$contactTel = '',$chooseSeats = '')
    {
        $method = 'qianmi.elife.train.order.create';

        $params = [
            "accountNo" => $accountNo,
            "accountPwd" => $accountPwd,
            "ticketModel" => $ticketModel,
            "trainNumber" => $trainNumber,
            "startTime" => $startTime,
            "contactName" => $contactName,
            "passagers" => $passagers,
            "itemIdTrain" => $itemIdTrain,
            "date" => $date,
            "to" => $to,
            "from" => $from,
            "contactTel" => $contactTel,
            "chooseSeats" => $chooseSeats,
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();
        $curl->setGetParams($params);
        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }


    /**
     * 支付火车票订单
     * 支付预定过的火车票订单：
        1.支付需在预定成功后半小时内完成，否则自动取消预定。
        2.支付状态前提：预定完成（state-2），未支付（billstate-0）且发车时间未过期。
     * @param string $tradeNo   订单编号
     * @throws \Exception
     */
    public function queryTrainOrderPay($tradeNo = '') {
        $method = 'qianmi.elife.train.order.pay';

        $params = [
            "tradeNo" => $tradeNo,
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();

        $curl->setGetParams($params);

        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }

    /**
     * 取消火车票订单
     * 交易中，取消整笔订单，状态前提：预定完成（state-2），未支付（billstate-0）。
     * @param string $tradeNo   订单编号
     * @throws \Exception
     */
    public function queryTrainOrderCancel($tradeNo = '') {
        $method = 'qianmi.elife.train.order.cancel';

        $params = [
            "tradeNo" => $tradeNo,
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();
        $curl->setGetParams($params);
        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }

    /**
     * 退订火车票订单
     * 交易完成，取消订单，支持选择子单退订：
        1.退订订单状态前提：已完成（state-1），已支付（ billstate 1）；
        2.人工充值的火车票，退订时，不自动退保险，需供货商人工操作退款；
        3.非人工充值的火车票，退订时，自动退保险。
        4.23：30-06：00为非服务时间，请勿在此时间段内操作退票。
     * @param string $orderNos   订单子单编号，多个时以‘,’分隔
     * @throws \Exception
     */
    public function queryTrainOrderRefund($orderNos = '') {
        $method = 'qianmi.elife.train.order.refund';

        $params = [
            "orderNos" => $orderNos,
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();
        $curl->setGetParams($params);
        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }

    /**
     * 查询火车票订单列表
     *查询火车票订单列表，分页返回
     * @throws \Exception
     */
    public function queryTrainOrderList($tradeNo = '',$startTime = '',$endTime = '',$sort = '',$supUserId = '',$pageNo = '',$pageSize = '',$orderStatus = '') {
        $method = 'qianmi.elife.train.orders.list';

        $params = [
            "tradeNo" => $tradeNo,
            "startTime" => $startTime,
            "endTime" => $endTime,
            "sort" => $sort,
            "supUserId" => $supUserId,
            "pageNo" => $pageNo,
            "pageSize" => $pageSize,
            "orderStatus" => $orderStatus,
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();
        $curl->setGetParams($params);
        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }

    /**
     * 查看整笔订单详情
     * @param string $tradeNo   订单编号
     * @throws \Exception
     */
    public function queryTrainOrderInfo($tradeNo = '') {
        $method = 'qianmi.elife.train.order.detail';

        $params = [
            "tradeNo" => $tradeNo,
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();
        $curl->setGetParams($params);
        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }

    /**
     * 查询指定车次的经停站信息
     * 用车次号+日期即可查询出该车次的具体经停信息
     * @param string $trainNumber   订单编号
     * @param string $date   查询日期
     * @throws \Exception
     */
    public function queryTrainStationList($trainNumber = '',$date = '') {
        $method = 'qianmi.elife.train.stopstations.list';

        $params = [
            "trainNumber" => $trainNumber,
            "date" => $date,
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();
        $curl->setGetParams($params);
        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }

    /**
     * 火车票乘客身份核验
     * 通过该接口验证乘客信息（证件号和手机）是否通过12306核验
        1. 若有乘客身份核验（status）未通过，需持证去火车站核验。
        2. 若有乘客手机核验（mobileStatus）未通过，需要用对应乘客手机号编辑校验码（captcha的值）发送至12306。
        3. 短信发送完成后调用lf.elife.train.identity.verification.result接口查询校验结果。
        4. 所有乘客都通过身份和手机核验才能预定火车票。
        5. 验证码30分钟内有效，建议尽快编辑短信发送，尽量缩短时间。
     * @param string $trainNumber   订单编号
     * @throws \Exception
     */
    public function queryTrainIdentityVerification($passagers = '') {
        $method = 'lf.elife.train.identity.verification';

        $params = [
            "passagers" => $passagers
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();
        $curl->setGetParams($params);
        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }

    /**
     * 火车票乘客身份核验结果查询
     * 1.结合身份核验接口lf.elife.train.identity.verification使用，查询核验结果。
        2.乘客手机号发完短信后调用此接口查询核验结果。
     * @throws \Exception
     */
    public function queryTrainIdentityVerificationResult($passagers = '') {
        $method = 'lf.elife.train.identity.verification.result';

        $params = [
            "passagers" => $passagers
        ];

        $params = $this->getBaseParams($method, $params);

        $curl = new Curl();
        $curl->setGetParams($params);
        $response = $curl->get($this->api);

        return $this->formatResponse($response);
    }

    private function formatResponse($response = '') {
        $res = json_decode($response, true);

        if (!empty($res['errorToken'])) {
            throw new Exception($res['subErrors'][0]['message']);
        }

        return $res;
    }
}